<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class GoodsDonate extends Backend
{

    /**
     * GoodsDonate模型对象
     * @var \app\admin\model\GoodsDonate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\GoodsDonate;
        $shopApple=new \app\common\model\ShopApply();
        $adminInfo=$shopApple->where('id','=',$this->auth->id)->find();
        $admin_id = $this->auth->getGroupIds()[0];
        $this->user_type=$adminInfo['shopcate_id'];//1药品 2检查 3采集
        $this->view->assign("goodsAttrList", $this->model->getGoodsAttrList());
        $this->view->assign("isShipList", $this->model->getIsShipList());
        $this->view->assign("freightTypeList", $this->model->getFreightTypeList());
        $this->view->assign("isRecommondList", $this->model->getIsRecommondList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getstatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("isGoodList", $this->model->getIsGoodList());
        $this->view->assign("isCheckingList", $this->model->getIsCheckingList());
        $this->view->assign("user_type",   $this->user_type);
        $this->view->assign("admin_id",  $admin_id);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
//        $admin_id = $this->auth->getGroupIds()[0];
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //判断用户身份
            //      $params['shop_id']=$this->auth->id;
            //获取店铺信息
            //如果不是
//            $adminModel=new Admin();
//            $shopInfo=$adminModel->where('id','=',$this->auth->id)->find();
            $where1=[];
            if ($this->auth->getGroupIds()[0] !=1 &&$this->auth->getGroupIds()[0]!=7){
                $where1['shop_id']=$this->auth->id;
            }
//            $where2['goods.status']=1;
//            $where1['`goods`.type']=3;
//            dd($where1);
            $total = $this->model
                ->with(['category1','user'])
                ->where($where)
                ->where($where1)
//                ->order($sort, $order)
                ->order('goods_donate.id desc')
                ->count();
            $list = $this->model
                ->with(['category1','user'])
                ->where($where)
                ->where($where1)
//                ->order($sort, $order)
                ->order('goods_donate.id desc')
                ->limit($offset, $limit)
//                ->fetchSql()
                ->select();
//            dd($list);

            foreach ($list as $row) {
                $row->getRelation('category1')->visible(['name']);
                $row->getRelation('user')->visible(['nickname','avatar']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $admin_id=$admin = Session::get('admin');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
//            $skuParams = $this->request->post('specdata/a');
//            $skuDatas = $this->request->post('sku/a');
//            if(empty($skuDatas)){
//                $this->error('请添加规格');
//            }

//            dd($params);
            //分割
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
//                    $checkModel=new \app\admin\model\GoodsCheck();
                    $params['shop_id']=$this->auth->id;
                    //获取店铺信息
                    $adminModel=new Admin();
                    $shopInfo=$adminModel->where('id','=',$this->auth->id)->where('is_shop','=',1)->find();
                    if (empty($shopInfo)){
                        $params['shop_id']=1;
                    }
//                    $params['is_checking']=2;
                    //查看当前用户是否有权限发布商品
//                    $shopApply=new \app\common\model\ShopApply();
//                    $shopApplyInfo=$shopApply->where('admin_id',$params['shop_id'])->find();


//                    $params['starttime']=strtotime($params['starttime']);
//                    $params['endtime']=strtotime($params['endtime']);
                    $params['uid']=1;
                    $result = $this->model->allowField(true)->save($params);
//                    $id = $this->model->id;
                    //商品新增结束后 将商品添加到待审核列表
//                    $checkModel->create(['goods_id'=>$id]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

//                    $this->saveParams($id,$skuParams,$skuDatas);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //查询运费模板
        //        $logList = Db::name('logistics')
        //            ->field('id,name')
        //            ->where('deletetime',null)
        //            ->select();
        $logList = [];
        //查询一级分类
        $cateList = Db::name('goods_category')
            ->field('id,name')
            ->where('status','normal')
            ->where('types','2')
//            ->where('type','2')
            ->where('pid','0')
            ->order('weigh ASC')
            ->select();
        $this->view->assign('cateList',$cateList);
        $this->view->assign('logList',$logList);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
//            $skuParams = $this->request->post('specdata/a');
//            $skuDatas = $this->request->post('sku/a');
////            dd($skuDatas);
//            if(empty($skuDatas)){
//                $this->error('请添加规格');
//            }
//            if($row['type']!=$params['type']){
//                $this->error('不支持更改商品类型');
//            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //   $params['shop_id']=$this->auth->id;
                    //获取店铺信息
//                    $adminModel=new Admin();
//                    $shopInfo=$adminModel->where('id','=',$this->auth->id)->where('is_shop','=',1)->find();
//                    if (empty($shopInfo)){
//                        $params['shop_id']=1;
//                    }
//                    $params['is_checking']=2;
//                    //查看当前用户是否有权限发布商品
//                    $shopApply=new \app\common\model\ShopApply();
//                    $shopApplyInfo=$shopApply->where('admin_id',$params['shop_id'])->find();
//                    if ($shopApplyInfo->shopcate_id==2){
//                        $this->error('检查商家不允许发布商品');
//                    }
//                    if ($shopApplyInfo->shopcate_id==3){
//                        $params['is_checking']=1;
//                        $params['is_ship']=0;
//                    }
//                    $params['starttime']=strtotime($params['starttime']);
//                    $params['endtime']=strtotime($params['endtime']);
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
//                    $this->saveParams($ids,$skuParams,$skuDatas);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        //查询规格
//        $specList = Db::name('goods_spec')
//            ->where('gid',$ids)
//            ->where('deletetime',null)
//            ->order('sort')
//            ->select();
//        if(!empty($specList)){
//            foreach ($specList as $k => $v){
//                $specValueList = Db::name('goods_spec_value')
//                    ->where('deletetime',null)
//                    ->where('gid',$ids)
//                    ->where('sid',$v['id'])
//                    ->order('sort')
//                    ->select();
//                $specList[$k]['values'] = $specValueList;
//            }
//        }
//        $skuList = Db::name('goods_sku')
//            ->where('gid',$ids)
//            ->where('deletetime',null)
//            ->select();
//        //将sku进行转化 用值当键
//        $new_arr = [];
//        foreach ($skuList as $k1 => $v1){
//            $new_arr[$v1['sku_data']] = $v1;
//        }

        //查询运费模板
        //        $logList = Db::name('logistics')
        //            ->field('id,name')
        //            ->where('deletetime',null)
        //            ->select();
//        $logList = [];
        //查询分类信息
        $cateList = Db::name('goods_category')
            ->field('id,name')
            ->where('status','normal')
            ->where('pid',0)
            ->where('types','1')
            ->order('weigh ASC')
            ->select();



//        $cateList1 = Db::name('goods_category')
//            ->field('id,name')
//            ->where('status','normal')
//            ->where('pid',$row['cid1'])
//            ->order('weigh ASC')
//            ->select();
//        $cateList2 = Db::name('goods_category')
//            ->field('id,name')
//            ->where('status','normal')
//            ->where('pid',$row['cid2'])
//            ->order('weigh ASC')
//            ->select();
        $this->view->assign('cateList',$cateList);
//        $this->view->assign('cateList1',$cateList1);
//        $this->view->assign('cateList2',$cateList2);
//        $this->view->assign('logList',$logList);

//        $row['starttime'] = date('Y-m-d H:i:s',$row['starttime'] );
//        $row['endtime'] = date('Y-m-d H:i:s',$row['endtime'] );

//        $this->view->assign(['specList'=>$specList,'skuList'=>json_encode($new_arr)]);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 保存规格
     */
    public function saveParams($id,$skuParams,$skuDatas){
        $specidarr = [];//不需要删除的规格名ID
        $specvalidarr = [];//不需要删除的规格值ID
        $skuarr = [];//不需要删除的skuID
        $arr = [];
        foreach ($skuParams as $k => $v){
            $old_k = $k;
            $spec = $v['spec'];
            $spec_value = isset($v['spec_value'])?$v['spec_value']:[];
            $specInsert = [
                'spec_name' => $spec['name'],
                'gid' => $id,
                'sort' => $spec['sort'],
                'is_checked' => !empty($spec['is_checked'])?$spec['is_checked']:0,
                'createtime' => time(),
            ];
            $have_spec_id = !empty($spec['id'])?$spec['id']:'';
            if(empty($have_spec_id)){
                $spec_id = Db::name('goods_spec')->insertGetId($specInsert);
            }else{
                $specInsert['updatetime'] = time();
                $suc = Db::name('goods_spec')->where('id',$have_spec_id)->update($specInsert);
                $spec_id = $have_spec_id;
            }
            if($spec_id){
                $new_k = $spec_id;
                $specidarr[] = $spec_id;
                if(!empty($spec_value)){
                    foreach ($spec_value as $k1 => $v1){
                        $old_value_k = $k1;
                        $spec_value_info = $v1;
                        $specValueInsert = [
                            'spec_val_name' => $spec_value_info['name'],
                            'sort' => $spec_value_info['sort'],
                            'is_checked' => !empty($spec_value_info['is_checked'])?$spec_value_info['is_checked']:0,
                            'createtime' => time(),
                            'gid' => $id,
                            'sid' => $spec_id
                        ];
                        $have_spec_value_id = !empty($spec_value_info['id'])?$spec_value_info['id']:'';
                        if(!empty($have_spec_value_id)){
                            $specValueInsert['updatetime'] = time();
                            $suc = Db::name('goods_spec_value')->where('id',$have_spec_value_id)
                                ->update($specValueInsert);
                            $spec_value_id = $have_spec_value_id;
                        }else{
                            $spec_value_id = Db::name('goods_spec_value')->insertGetId($specValueInsert);
                        }
                        if($spec_value_id){
                            $new_value_k = $spec_value_id;
                            $specvalidarr[] = $spec_value_id;
                            $new_str = $new_k .'-'. $new_value_k;
                            $old_str = $old_k .'-'. $old_value_k;
                            $arr_info = $new_str .','. $old_str.','.$spec_value_info['name'];
                            $arr[] = $arr_info;
                        }
                    }
                }
            }
        }
        if(!empty($arr)){
            $inserSku = [];
            $prcie_arr = [];
            foreach ($skuDatas as $k2 => $v2){
                $sku_data = explode(',',$v2['data']);
                $name_arr = [];
                foreach ($arr as $k3 => $v3){
                    $findspec = explode(',',$v3);
                    $old_value = $findspec[1];
                    $new_value = $findspec[0];
                    $name = $findspec[2];
                    $name_arr[$new_value] = $name;
                    if(in_array($old_value,$sku_data)){
                        $ks = array_search($old_value,$sku_data);
                        $sku_data[$ks] = $new_value;
                    }
                }
                asort($sku_data);
                $name_str = '';
                foreach ($sku_data as $sku_k => $sku_v){
                    $name_str .= ' '.$name_arr[$sku_v];
                }
                if(!empty($name_str)){
                    $name_str = trim($name_str);
                }
                $sku = [
                    'sku_name' => $name_str,
                    'sku_data' => implode($sku_data,','),
                    'price' => $v2['price'],
                    'weight' => $v2['weight'],
                    'sku_thumbnail' => $v2['sku_thumbnail'],
                    'sku_stock' => $v2['sku_stock'],
                    'gid' => $id,
                    'createtime' => time()
                ];
                $prcie_arr[] = $sku['price'];
                $have_sku_id = !empty($v2['id'])?$v2['id']:'';
                if(!empty($have_sku_id)){
                    $sku['updatetime'] = time();
                    $suc = Db::name('goods_sku')
                        ->where('id',$have_sku_id)
                        ->update($sku);
                    $skuarr[] = $have_sku_id;
                }else{
                    $ids = Db::name('goods_sku')->insertGetId($sku);
                    if($ids){
                        $skuarr[] = $ids;
                    }
                }

                $inserSku[] = $sku;
            }
            //获取数组中的最大值 和 最小值
            if(!empty($prcie_arr)){
                $max_price = max($prcie_arr);
                $min_price = min($prcie_arr);
                Db::name('goods')
                    ->where('id',$id)
                    ->update(['max_price' => $max_price , 'min_price' => $min_price]);
            }
        }
        //删除规格名（软）
        Db::name('goods_spec')
            ->where('id','not in',$specidarr)
            ->where('deletetime',null)
            ->where('gid',$id)
            ->update(['deletetime'=>time()]);
        //删除规格值（软）
        Db::name('goods_spec_value')
            ->where('id','not in',$specvalidarr)
            ->where('deletetime',null)
            ->where('gid',$id)
            ->update(['deletetime'=>time()]);
        Db::name('goods_sku')
            ->where('id','not in',$skuarr)
            ->where('deletetime',null)
            ->where('gid',$id)
            ->update(['deletetime'=>time()]);

    }

    /**
     * 获取分类
     */
    public function getcateList(){
        if($this->request->isAjax()){
            $params = $this->request->post();
            if(empty($params)){
                $this->error('参数错误');
            }
            $pid = $params['pid'];
            $list = Db::name('goods_category')
                ->field('id,name')
                ->where('pid',$pid)
                ->order('weigh ASC')
                ->select();
            $html = '';
            if(!empty($list)){
                foreach ($list as $k => $v){
                    $html.=" <option value='".$v['id']."'>".$v['name']."</option>";
                }
            }
            $this->success('请求成功','',$html);
        }
    }
    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 99999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $good=new \app\admin\model\GradeGoods();
        if(!empty($custom['category_id'])){
            $goods_ids=$good->where('cat_id3','=',$custom['category_id'])->column('goods_id');
            $total = $this->model->where($where)->where('state','=',1)->where('status','=',1)->whereNotIn('id',$goods_ids)->count();
            if ($total > 0) {
                if (is_array($adminIds)) {
                    $this->model->where($this->dataLimitField, 'in', $adminIds);
                }
                $datalist = $this->model->where($where)
                    ->whereNotIn('id',$goods_ids)
                    ->where('state','=',1)->where('status','=',1)
                    ->order($order)
                    ->page($page, $pagesize)
                    ->field($this->selectpageFields)
                    ->select();
                foreach ($datalist as $index => $item) {
                    unset($item['password'], $item['salt']);
                    $list[] = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                        'pid'       => isset($item['pid']) ? $item['pid'] : 0
                    ];
                }
                if ($istree && !$primaryvalue) {
                    $tree = Tree::instance();
                    $tree->init(collection($list)->toArray(), 'pid');
                    $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                    if (!$ishtml) {
                        foreach ($list as &$item) {
                            $item = str_replace('&nbsp;', ' ', $item);
                        }
                        unset($item);
                    }
                }
            }
        }

        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    public function selectpage1()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //        dd($custom);
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 99999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    public function selectpagecoupon()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //        dd($custom);
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 99999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $adminModel=new Admin();
        $shopInfo=$adminModel->where('id','=',$this->auth->id)->where('is_shop','=',1)->find();
        $where1=[];
        if (!empty($shopInfo)){
            $where1['shop_id']=$this->auth->id;
        }
        $total = $this->model->where($where)->where($where1)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->where($where1)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
}
